package cn.zhc.com.base;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;


import butterknife.BindView;
import cn.zhc.com.R;
import cn.zhc.com.event.EventInfo;


/**
 * Created by zhouhongchun on 2016/3/28.
 */
public class BaseWebView extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.pb_load)
    ProgressBar pb_load;
    @BindView(R.id.ll_web)
    LinearLayout ll_web;
    public static final String URL = "url";
    String url;


    public final static int FILECHOOSER_RESULT_CODE = 1;
    public ValueCallback<Uri[]> uploadMessageAboveL;
    public ValueCallback<Uri> uploadMessage;



    @Override
    protected int bindLayout() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected void init() {
        url = getIntent().getStringExtra(URL);

        webview.requestFocus();
        webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webview.setHorizontalScrollBarEnabled(false);
        webview.setHorizontalScrollbarOverlay(true);
        /**
         * native和H5交互，提供一个接口，并封装相应的方法供h5调用
         */
        webview.addJavascriptInterface(new JsInteration(), "call");
        webview.removeJavascriptInterface("searchBoxJavaBredge_");

        webview.setWebViewClient(new SampleWebViewClient());
        webview.setWebChromeClient(webClient);
        initSetting();
        webview.loadUrl(url);


    }


    private void initSetting() {
        WebSettings mWebSettings = webview.getSettings();
        mWebSettings.setAllowFileAccess(true);
        // 设置可以支持缩放
        mWebSettings.setSupportZoom(true);
        // 设置出现缩放工具
        mWebSettings.setBuiltInZoomControls(false);
        //扩大比例的缩放
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        //缓存设置，暂时要求去除缓存
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }




    /**
     * 不使用手机的内置浏览器
     */
    private class SampleWebViewClient extends WebViewClient {


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
//            ll_web.removeView(webview);
//            final View inflate = getLayoutInflater().inflate(R.layout.fragment_a_load_fail, null);
//            inflate.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ll_web.removeAllViews();
//                    ll_web.addView(webview);
//                    webview.loadUrl(url);
//                }
//            });
//            ll_web.addView(inflate);
        }
    }

    /**
     * 网页的进度监听，并解决H5文件选择的问题
     */
    WebChromeClient webClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (pb_load != null ){
                if (newProgress == 100) {
                    pb_load.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == pb_load.getVisibility()) {
                        pb_load.setVisibility(View.VISIBLE);
                    }
                    pb_load.setProgress(newProgress);
                }
            }

            super.onProgressChanged(view, newProgress);
        }

        //The undocumented magic method override
        //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            uploadMessage = uploadMsg;
            openImageChooserActivity();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            uploadMessage = uploadMsg;
            openImageChooserActivity();
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            uploadMessage = uploadMsg;
            openImageChooserActivity();

        }

        //For Android 5.0
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }

    };

    private void openImageChooserActivity() {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT,
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, FILECHOOSER_RESULTCODE);

        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, FILECHOOSER_RESULT_CODE);
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case FILECHOOSER_RESULT_CODE:
                    if (null != uploadMessage) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadMessage.onReceiveValue(result);
                        uploadMessage = null;
                    }
                    if (null != uploadMessageAboveL) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadMessageAboveL.onReceiveValue(new Uri[]{result});
                        uploadMessageAboveL = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadMessage) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
            if(null != uploadMessageAboveL){
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }

        }


    }




    /**
     * 封装native的方法，提供给h5调用
     */
    private class JsInteration {


        /**
         * 关闭页面
         */
        @JavascriptInterface
        public void closeActivity() {
            webview.post(new Runnable() {
                @Override
                public void run() {
                    BaseWebView.this.finish();
                }
            });
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        webview.reload();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onEventBusMainThread(EventInfo mEventInfo) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.destroy();
        }
    }

    //  两次退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webview.canGoBack()) {
                webview.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}



